import xlrd
import urllib
import requests
import xlwt
import time
import time
import json
import datetime
from datetime import datetime
from xlrd import xldate_as_tuple
from urllib.parse import urljoin
from urllib.parse import urlparse
from urllib.parse import urlunparse
from posixpath import normpath
from IPython.utils.traitlets import CBool, Unicode
fname =r'C:\Users\Zhou   Jia   Bin\Desktop\678.xlsx'
bk = xlrd.open_workbook(fname,encoding_override='utf-8')
table = bk.sheet_by_index(0)

all_data = []
for n in range(1,5):
    longitude = table.cell(n, 5).value
    latitude = table.cell(n, 6).value
    dateFormat = table.cell(n, 12).value
    time_1 = table.cell(n,14).value
    #print(dateFormat)
    #date_time=datetime.strptime(dateFormat,'%Y/%m/%d %H:%M:%S')
    #print(date_time)
    #print(dateFormat.strip().split('\t')[0])
   # print(type(dateFormat.strip().split('\t')[0]))
    #print(longitude)
    #print(latitude)
       # 转成datetime对象
    datef=dateFormat+time_1
    date_f= datetime(*xldate_as_tuple(datef,0))
    cell = date_f.strftime('%Y/%d/%m %H:%M:%S')
   # print(datef)
    #print(date_f)
    #print(type(date))
    #下面2行代码把py中的时间搞成了unix时间
    #dtime=datetime.date(date_f)
    ans_time =time.mktime(time.strptime(cell,'%Y/%d/%m %H:%M:%S'))
    #print(ans_time)
    #cell = date.strftime('%Y/%d/%m')
   # print(cell)
    data = {'longitude': longitude, 'latitude': latitude, 'Date':int(ans_time),'Time':time_1}
    all_data.append(data)
def myjoin(base, url):
        url1 = urljoin(base, url)
        arr = urlparse(url1)
        path = normpath(arr[2])
        return urlunparse((arr.scheme, arr.netloc, path, arr.params, arr.query, arr.fragment))
def write2file(content):
    # 存为json形式文本文件
    for item in content:
        with open(t+'weather.txt', 'a', encoding='utf-8') as f:
            f.write(json.dumps(item, ensure_ascii=False)+'\n')
if __name__ == "__main__":
     for i in all_data:
         url="252b00e6d8a8ddf01472a83e5946533f/"+str(i["latitude"])+','+str(i["longitude"])+','+str(i["Date"])
         cn1="https://api.darksky.net/forecast/"
        #  print(cn1)
         print(myjoin(cn1,url))
         finallurl=myjoin(cn1,url)
         strhtml =requests.get(finallurl)
         strhtml.encoding="utf8"
         time.sleep(1)
         dic=strhtml.json()
         print(dic['latitude'])
         print(dic['longitude'])
         print(dic['currently'])
         content=[]
         content.append({
         'latitude':dic['latitude'],
         'longitude':dic['longitude'],
         'currently':dic['currently']
         })
         t = str(datetime.now())[:13]
         write2file(content)
    # print(i["longitude"])
